import { createRouter, createWebHistory } from "vue-router";
import Login from "../views/Login.vue";
import SchoolList from "../views/SchoolList.vue";
import SchoolForm from "../views/SchoolForm.vue";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      redirect: "/schools",
    },
    {
      path: "/login",
      name: "login",
      component: Login,
      meta: { requiresAuth: false },
    },
    {
      path: "/schools",
      name: "schools",
      component: SchoolList,
      meta: { requiresAuth: true },
    },
    {
      path: "/schools/add",
      name: "schoolAdd",
      component: SchoolForm,
      meta: { requiresAuth: true },
    },
    {
      path: "/schools/edit/:id",
      name: "schoolEdit",
      component: SchoolForm,
      props: true,
      meta: { requiresAuth: true },
    },
  ],
});

// 添加导航守卫，处理鉴权
router.beforeEach((to, from, next) => {
  console.log("router.beforeEach");

  const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth);

  // 强制刷新登录状态，确保localStorage数据正确加载
  if (isLoggedIn && from.path === "/login" && to.path === "/schools") {
    // 如果是从登录页面直接跳转到学校列表页面，直接放行
    return next();
  }

  if (requiresAuth && !isLoggedIn) {
    next("/login");
  } else if (to.path === "/login" && isLoggedIn) {
    next("/schools");
  } else {
    next();
  }
});

export default router;
